<template>
  <g-btn
    :icon="icon"
    :text="text"
    :eventName="'Import'"
    @callback="callback($event)"
    :class="[className, 'flex-center']"
  ></g-btn>
  <a-modal
    class="excel-import"
    :visible="isVisible"
    :title="l('ImportFromExcel')"
    @cancel="handleCancel()"
    :maskClosable="true"
    cancelText="null"
    okText="null"
    :centered="true"
    :closable="true"
    :footer="null"
  >
    <template v-if="showType == 'button'">
      <a-upload
        :action="importExcelUrl"
        accept="xls/*"
        withCredentials="false"
        headers="uploadHeaders"
        @change="handleChange($event)"
      >
        <a-button><i a-icon nzType="upload"></i> {{ l(buttonTest) }}</a-button>
      </a-upload>
    </template>
    <!-- 更新日志：2021/9/2 把[nzMultiple] 更新为false，禁止选择多个文件-->
    <template v-else>
      <a-upload
        type="drag"
        :action="importExcelUrl"
        accept="xls/*"
        :withCredentials="false"
        :multiple="false"
        :headers="uploadHeaders"
        @change="handleChange"
        v-model:fileList="fileList"
      >
        <template #itemRender="{ file }">
          <a-card :bodyStyle="{ padding: '5px 10px' }">
            <div class="fileDiyList">
              <div class="left">
                <svg class="icon gcticons" aria-hidden="true">
                  <use xlink:href="#gctwenjian"></use>
                </svg>
                <p>{{ file.name }}</p>
              </div>
              <div class="right">
                <div class="SorE">
                  <div
                    class="t"
                    v-if="
                      (file.status === 'done' || file.status === 'success') &&
                      file?.error &&
                      !file?.error?.hasError
                    "
                  >
                    <svg class="icon gcticons" aria-hidden="true">
                      <use xlink:href="#gctchenggong"></use>
                    </svg>
                  </div>
                  <div
                    class="f"
                    v-if="
                      (file.status === 'done' || file.status === 'success') &&
                      file?.error &&
                      file?.error?.hasError
                    "
                  >
                    <p v-if="file?.error?.labelingErrorFileDto" @click="downError(file)">
                      {{ l('DowloadErrorLabels') }}
                    </p>
                    <a-tooltip
                      class="detail"
                      trigger="'click'"
                      :overlayStyle="{ borderRadius: '6px' }"
                      overlayClassName="tipCardFile"
                    >
                      <template #title>
                        <!-- <p>{{ item.error | handleData }}</p> -->
                        <div class="boxTip">
                          <div class="item" v-for="(err, idx) in transform(file.error)" :key="idx">
                            <p>{{ err?.title }}</p>
                            <p v-for="(child, idx) in err.content" :key="idx">
                              <span>{{ child.key }}</span>
                              <span>：</span>
                              <span>{{ child.value }}</span>
                            </p>
                          </div>
                        </div>
                        <!-- <ng-container *ngFor="let data of item.error.templateErrors">
                            <a-alert
                              nzType="warning"
                              nzShowIcon
                              nzCloseable
                              [nzMessage]="data.message + '字段为：' + data.requireColumnName"
                            >
                            </a-alert>
                          </ng-container>

                          <ng-container *ngFor="let data of item.error.rowErrors">
                            <a-alert
                              nzType="warning"
                              nzShowIcon
                              nzCloseable
                              [nzMessage]="'第' + data.rowIndex + '行'"
                              [nzDescription]="fieldErrorsShow"
                            >
                            </a-alert>

                            <ng-template #fieldErrorsShow>
                              <pre>{{ data.fieldErrors | importError }}</pre>
                            </ng-template>
                          </ng-container> -->
                      </template>
                      <!-- <i class="gcticons gctchakanyanjing"> </i> -->
                      <svg class="icon gcticons" aria-hidden="true">
                        <use xlink:href="#gctchakanyanjing"></use>
                      </svg>
                      <span>{{ l('ErrorDetails') }}</span>
                    </a-tooltip>
                  </div>
                </div>
                <div class="active">
                  <svg @click="deleteItem(file)" class="icon gcticons" aria-hidden="true">
                    <use xlink:href="#gctshanchu3"></use>
                  </svg>
                </div>
              </div>
            </div>
          </a-card>
        </template>
        <p class="ant-upload-drag-icon">
          <!-- 默认样式 -->
          <!-- <i a-icon nzType="inbox"></i> -->
          <!-- <i class="gcticons gctshangchuan1 upload-style"></i> -->
          <svg v-if="icon" class="icon gcticons upload-style icon-1" aria-hidden="true">
            <use xlink:href="#gctshangchuan1"></use>
          </svg>
        </p>
        <p class="ant-upload-text">{{ l('ClickAreaToUploadFiles') }}</p>
      </a-upload>
    </template>
  </a-modal>
</template>

<script lang="ts">
  import { AppComponentBase } from '/@/shared/component-base';
  import { DataRowErrorInfo } from '/@/shared';
  import { FileDto } from '/@/shared';
  import { TemplateErrorInfo } from '/@/shared';
  import FileDownloadService from '/@/shared/utils/file-download.service';
  import { AppConsts } from '/@/abpPro/AppConsts';

  import GBtn from '../g-btn/index.vue';
  import { UploadChangeParam, UploadFile } from 'ant-design-vue/es/upload';
  import { transform } from './handleData';

  interface iData {
    importExcelUrl: string;
    fileList: UploadFile[];
    uploadHeaders: any;
    isVisible: boolean;
    isConfirmLoading: boolean;
    templateErrors: TemplateErrorInfo[] | undefined;
    rowErrors: DataRowErrorInfo[] | undefined;
    hasError: boolean;
    labelingErrorFileDto: FileDto | undefined;
  }
  export default {
    mixins: [AppComponentBase],
    components: { GBtn },
    emits: ['fileUploadedSuccessEvent'],
    props: {
      /** 上传文件展示方式
       * button 按钮展示
       * drag 拖拽展示
       */
      showType: {
        type: String,
        default: 'drag',
      },

      /** 上传按钮名称多语言编码 */
      buttonTest: {
        type: String,
        default: '选择',
      },

      type: {
        type: String,
        default: 'primary',
      },

      icon: {
        type: String,
        default: 'gctshangchuan',
      },

      text: {
        type: String,
        default: '',
        // l('ImportFromExcel')
      },
      /** 上传成功事件 */
      // @Output() fileUploadedSuccessEvent = new EventEmitter<string>();
      className: {
        type: String,
        default: 'info',
      },
    },
    created() {
      this.initPage();
    },
    data(): iData {
      return {
        /** 上传Excel接口地址 */
        importExcelUrl: '',

        //文件列表的双向绑定
        fileList: [],
        uploadHeaders: '',

        isVisible: false,

        isConfirmLoading: false,

        /** 模板错误 */
        templateErrors: undefined,
        /** 验证错误 */
        rowErrors: undefined,
        /** 是否存在导入错误 */
        hasError: false,
        /** 错误标注文件 */
        labelingErrorFileDto: undefined,
      };
    },
    methods: {
      transform(data: any) {
        return transform(data);
      },
      initPage() {
        this.importExcelUrl =
          AppConsts.remoteServiceBaseUrl + '/api/services/app/FileManagement/UploadTempFile';

        // 设置头部信息
        this.uploadHeaders = {
          Authorization: 'Bearer ' + abp.auth.getToken(),
        };

        this.fileDownloadService = FileDownloadService;
      },
      callback(value: any) {
        this.showModal();
      },

      handleChange(info: UploadChangeParam) {
        this.fileList = [...info.fileList];
        console.log(this.fileList, '执行');
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done' || info.file.status === 'success') {
          console.log('上传成功');

          if (info.file.response.error) {
            this.message.warn(this.l(info.file.response.error.message));
          } else {
            console.log('走到这里了', this.fileList);

            this.$emit('fileUploadedSuccessEvent', info.file.response.result.fileToken);
          }

          // this.msg.success(`${info.file.name} file uploaded successfully`);
        } else if (info.file.status === 'error') {
          console.log('error');

          // this.msg.error(`${info.file.name} file upload failed.`);
        }
      },

      showModal(): void {
        this.isVisible = true;
      },

      downError(item) {
        this.fileDownloadService.downloadTempFile(item.error.labelingErrorFileDto);
      },

      deleteItem(item) {
        this.fileList = this.fileList.filter((v) => v.uid !== item.uid);
      },

      handleCancel(): void {
        // this.templateErrors = undefined;
        // this.rowErrors = undefined;
        // this.labelingErrorFileDto = undefined;
        // this.hasError = undefined;
        this.fileList = [];
        this.isVisible = false;
      },

      /** 初始化导入结果 */
      initImportReturn(errors: any): any {
        if (errors) {
          // this.templateErrors = errors.templateErrors;
          // this.rowErrors = errors.rowErrors;
          // this.hasError = errors.hasError;
          // this.labelingErrorFileDto = errors.labelingErrorFileDto;
          console.log(errors, this.fileList);
          this.fileList[this.fileList.length - 1].error = errors;
          // this._cdr.detectChanges();

          if (!errors.hasError) {
            // this.isVisible = false;
            // 维护多语言
            this.notify.success(this.l('UploadSuccess'));
          }
        }
      },
      handleData(value) {
        console.log(value, 'value');
        const data: FileErrors[] = [];
        const rowErrors = value.rowErrors;
        const hasError = value.hasError;
        const templateErrors = value.templateErrors;
        if (hasError) {
          if (rowErrors) {
            rowErrors.forEach((element) => {
              const item = new FileErrors();
              item.title = `第${element.rowIndex}行`;
              for (let i in element.fieldErrors) {
                const child = new FileErrorsItemArray();
                child.key = i;
                child.value = element.fieldErrors[i];
                item.content.push(child);
              }
              data.push(item);
            });
          }
          if (templateErrors) {
            templateErrors.forEach((element) => {
              const item = new FileErrors();
              item.title = element.columnName;
              item.level = element.errorLevel;
              const child = new FileErrorsItemArray();
              child.key = element.requireColumnName;
              child.value = element.message;
              item.content.push(child);
              data.push(item);
            });
          }
        }

        return data;
      },
    },
  };
</script>

<style lang="less" scoped>
  .ui-messages ul {
    display: block !important;
  }

  // .excel-import .ant-modal-content {
  //   width: 120vh !important;
  //   height: 85vh !important;
  // }

  g-btn {
    margin-right: 20px;
  }

  .ant-upload.ant-upload-drag:not(.ant-upload-disabled) {
    border-color: #53a6ff;
    background-color: #e6f7ff;
  }

  .ant-upload.ant-upload-drag:not(.ant-upload-disabled):hover {
    background-color: #d7f0fc;
    border-color: #53a6ff;
  }
  .gcticons.upload-style {
    color: #6bc3ec;
    font-size: 48px;
  }

  .ant-upload.ant-upload-drag p.ant-upload-text {
    color: #5ebde9;
  }

  //
  .ant-card-body {
    background: #ffffff;
    box-shadow: 0px 8px 8px rgba(101, 176, 255, 0.1);
    opacity: 1;
    border-radius: 4px;
    margin: 0;
    margin-top: 8px;
    border-color: transparent;
    & > * {
      box-sizing: border-box;
    }
    // box-shadow: 0 1px 1px -2px rgb(0 0 0 / 16%), 0 3px 4px 0 rgb(0 0 0 / 12%), 0 2px 12px 1px rgb(0 0 0 / 9%);
    .fileDiyList {
      //布局样式
      height: 30px;
      justify-content: space-between;
      p {
        margin: 0;
      }
      &,
      .right,
      .left,
      .SorE .f {
        display: flex;
        align-items: center;
      }
      .left {
        // display: flex;
        // align-items: center;
        margin-right: 25px;
        i {
          background-image: linear-gradient(#007bff, #8fbff2);
          background-clip: text;
          color: transparent;
        }
        p {
          padding-left: 10px;
        }
      }
      .right {
        flex-grow: 1;
        justify-content: space-between;
        .active {
          i {
            cursor: pointer;
          }
        }

        .SorE {
          .f {
            color: #ff1d1d;
            p,
            .detail span {
              font-size: 12px;
              margin-right: 5px;
              cursor: pointer;
            }
            .detail {
              margin-left: 8px;
              display: flex;
              align-items: center;
              span {
                margin-left: 2px;
              }
            }
          }
          .t {
            color: #14db98;
          }
        }
      }
    }
  }
  .info {
    color: #009ef7;
    background-color: #f1faff;
    border-color: #f1faff;
    border-radius: 4px;
    border-width: 1px;
    &:hover {
      color: #fff;
      background-color: #009ef7;
      border-color: #009ef7;
    }
  }
  .flex-center {
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
